package com.xcdh.orm.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xcdh.orm.entity.OrmDataSource;
import com.xcdh.orm.mapper.DcmsDataSourceMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
@Slf4j
public class DataSourceCache implements InitializingBean {
    public static final Map<String, OrmDataSource> DATA_SOURCE_MAP = new HashMap<>();

    @Autowired
    DcmsDataSourceMapper dcmsDataSourceMapper;

    @Override
    public void afterPropertiesSet() throws Exception {
        initDataSourceCache();
    }
// 初始化数据源
    public void initDataSourceCache() {
        try {
            LambdaQueryWrapper<OrmDataSource> queryWrapper = new LambdaQueryWrapper<>();
            List<OrmDataSource> dataSourcesList = dcmsDataSourceMapper.selectList(queryWrapper);
            dataSourcesList.forEach(item -> {
                try {
                    DATA_SOURCE_MAP.put(item.getDsName(),item);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

            });
            log.info("dataSource.size = "+DATA_SOURCE_MAP.entrySet().size());
        }catch (Exception e) {
            log.error("init dataSource error: {}",e.getMessage());
        }
    }

    public OrmDataSource getDataSource(String key){
        return DATA_SOURCE_MAP.get(key) ;
    }


}
